#!/usr/bin/python

import os
import shutil
import pygame
import subprocess
from sys import exit
from pygame.locals import *

FOLDER = os.path.join(os.path.expanduser("~"), "") # if you want a subfolder, just add it between
                                                   # the quotation marks. Remember the / at the end!
pygame.init()

screen_width = 640 # this paragraph is just your standard pygame stuff
screen = pygame.display.set_mode((screen_width, 480), RESIZABLE, 32)
pygame.display.set_caption("File Browser")
screen.fill((255, 255, 255))

def loading(directory):
    font = pygame.font.Font(None, 40) # this paragraph sets varibles related to the loading screen
    text = font.render("LOADING", True, (0,0,0), (255,255,255))
    eta = font.render(current_dir, True, (0,0,0), (255, 255, 255))
    etapos = screen_width/2 - eta.get_rect().width/2
    files = [f for f in os.listdir(directory)]
    thumbs = [f for f in os.listdir("thumbs/")]
    thumb_size = 70
    extensions = ".jpg .png .bmp .gif .JPG .PNG .BMP .GIF".split()
    images = []
    for image in files:
        if image in thumbs:
            pass
        else:
            for ext in extensions:
                if ext in image[-4:]:
                    images.append(image)
    i = 0
    x = 0
    for i in range(len(images)):
        process = subprocess.Popen(["totem-video-thumbnailer", "-s", str(thumb_size), "-r", directory + images[i], "thumbs/" + images[i]])
        while process.poll() == None: # this loops while the thumbnailer is busy. Displays loading information.
            event = pygame.event.poll()
            if event.type == QUIT:
                process.kill()
                exit()
            screen.fill((255, 255, 255))
            screen.blit(text, (x, 200))
            screen.blit(eta, (etapos, 300))
            textrect = text.get_rect()
            x += 1
            if x > screen_width:
                x = 0 - textrect.width
            pygame.display.update()
        i += 1

folder_icon = pygame.image.load("icons/folder.png").convert()
unknown_icon = pygame.image.load("icons/unknown.png").convert()
text_icon = pygame.image.load("icons/text.png").convert()
net_icon = pygame.image.load("icons/net.png").convert()
zip_icon = pygame.image.load("icons/zip.png").convert()
code_icon = pygame.image.load("icons/code.png").convert()
music_icon = pygame.image.load("icons/music.png").convert()
def refresh(current_dir):
    filelist = [] # this paragraph set some varibles for loading files
    files = [f for f in os.listdir(current_dir)]
    thumbs = [f for f in os.listdir("thumbs/")]
    for item in files:     # this whole thing adds the items in the directory to
        if item[0] == ".": # the list "filelist" as tuples (icon, name, rect, type)
            pass
        elif item in thumbs: 
            nail = pygame.image.load("thumbs/" + item).convert()
            filelist.append((nail,item, nail.get_rect(), "image")) # note: these are tuples.
        elif item[-5:] in [".epub", ".docx", ".mobi"]:
            filelist.append((text_icon, item, text_icon.get_rect(), "text"))
	elif item[-4:] in [".txt", ".doc", ".odt", ".pdf", ".abw", ".rtf", ".lit"]:
            filelist.append((text_icon, item, text_icon.get_rect(), "text"))
	elif item[-4:] in [".zip", ".rar"]:
            filelist.append((zip_icon, item, zip_icon.get_rect(), "zip"))
        elif item[-4:] in [".htm", ".css", ".xml"]:
            filelist.append((net_icon, item, net_icon.get_rect(), "net"))
	elif item[-4:] in [".mp3", ".ogg", ".mid"]:
            filelist.append((music_icon, item, music_icon.get_rect(), "music"))
        elif item[-5:] in [".html"]:
            filelist.append((net_icon, item, net_icon.get_rect(), "net"))
        elif item[-8:] in [".torrent"]:
            filelist.append((net_icon, item, net_icon.get_rect(), "net"))
	elif item[-3:] in [".py"]:
	    filelist.append((code_icon, item, code_icon.get_rect(), "code"))
        elif os.path.isdir(current_dir + item):
            filelist.append((folder_icon, item, folder_icon.get_rect(), "folder"))
        else: 
            filelist.append((unknown_icon, item, unknown_icon.get_rect(), "unknown"))
    return (filelist, files, thumbs)

up_icon = pygame.image.load("icons/up.png").convert() # loads in up icon used in the navbar
def navbar(x, y, event, current_dir): # the bar with the up button and the directory info
    pwd = font.render(current_dir, True, (0,0,0), (255,255,255))
    screen.blit(pwd, (30, 0))
    screen.blit(up_icon, (0,0))
    if up_icon.get_rect().collidepoint(x,y):
        pygame.draw.rect(screen, (255,0,0), up_icon.get_rect(), 2)
        if event.type is MOUSEBUTTONDOWN:
            if current_dir[-1] == "/":
                current_dir = os.path.split(current_dir)[0] # this is to get rid of trailing slash, if exists. Very hacky, will be removed later.
            current_dir = os.path.split(current_dir)[0] + "/"
    return current_dir

thumb_size = 70 # this paragraph sets varibles relating to displaying the thumbnails and icons
padding = 10
current_dir = os.path.expanduser("~") + "/"
old_dir = None
font = pygame.font.Font(None, 25)
smallfont = pygame.font.Font(None, 16)
navbar_height = 20
yscroll = navbar_height

while True: #main loop
    filelist, files, thumbs = refresh(current_dir)    
    if current_dir != old_dir:
        loading(current_dir)
        filelist, files, thumbs = refresh(current_dir)
        old_dir = current_dir
        yscroll = navbar_height
        
    screen.fill((255, 255, 255)) 
    
    event = pygame.event.poll() # Event stuff
    if event.type == QUIT:
	shutil.rmtree("thumbs")
	os.mkdir("thumbs")
        exit()
    if event.type == VIDEORESIZE:
        screen_width = event.size[0]
        filelist, files, thumbs = refresh(current_dir) # so that when you resize the screen, the
                                     # thumbnails will rearange themselves to fit.
        pygame.display.set_mode(event.size, RESIZABLE, 32)
        
    pressed_keys = pygame.key.get_pressed() #this paragraph deals with scrolling up and down
    if pressed_keys[K_DOWN]:
        yscroll -= 5
    if pressed_keys[K_UP]:
        yscroll += 5
        
    x = 0 + padding # sets x... 
    y = yscroll     # and y coords for the thumbnails  
    for item in filelist:
        if x + thumb_size + padding > screen_width:
            y += thumb_size + padding
            x = 0 + padding
        screen.blit(item[0], (x,y+yscroll))
        item[2].topleft = (x,y+yscroll)
        x += thumb_size + padding
        
    x, y = pygame.mouse.get_pos() # same varible names, different values.
    for item in filelist:
        if item[2].collidepoint(x, y): # note: collidepoint is a Rect() object.
            screen.blit(smallfont.render(item[1], True, (0,0,0), (255,255,255)), (0, 462))
            pygame.draw.rect(screen, (255, 0, 0), item[2], 2) # the red outline. The last argument --
            if event.type == MOUSEBUTTONDOWN:                 # the 2 -- is the width.
                if item[3] == "image":
                    subprocess.Popen(["eog", current_dir + item[1]]) # forks eog
                if item[3] == "folder":
                    current_dir = os.path.join(current_dir, item[1] + "/")
    current_dir = navbar(x, y, event, current_dir) # this is at the end so it is drawn above the files
    pygame.display.update()
